import {Component, OnInit, Input, inject, ViewChild, AfterViewChecked} from '@angular/core';
import {User} from '../../models/User';
import { UserService } from '../../service/userService';
import { Loginauth } from '../../service/loginauth';
import {NgForm} from '@angular/forms';
import {NavigationExtras, Router} from '@angular/router';
import {Location} from '@angular/common';
import { LoginService } from '../../service/loginService';

@Component({
  templateUrl: './updatepsw.html',
  styleUrls: ['./updatepsw.css'],
})

export class UpdatepswComponent implements AfterViewChecked, OnInit {
  messages = {
    password: '',
    newPassword: '',
    confirmPassword: ''
  };
  updateUser: User;
  @ViewChild('securityForm')
  securityForm: NgForm;

  ngAfterViewChecked() {
    // Angular的“单向数据流”规则禁止在一个视图已经被组合好之后再更新视图.而此时已组合好
    if (this.securityForm) {
      this.securityForm.valueChanges.subscribe(data => this.checkValidate());
    }
  }

  constructor(
    private userService: UserService,
    private loginauthService: Loginauth,
    public router: Router,
    private location: Location,
    private loginService: LoginService
  ) {
  }

  ngOnInit() {
    // 拷贝，内存分配心得user
    this.updateUser = {...this.loginService.user};
    this.updateUser.address = '';
  }

  onSubmit() {
    this.checkValidate(true);
    if (this.securityForm.invalid) {
      return false;
    }
    delete this.updateUser.salt;
    delete this.updateUser.openid;
    this.userService.changePassword(this.updateUser).subscribe((res) => {
      if (res.success && res.res) {
         this.router.navigate(['/login']);
      } else if (!res.success) {
        alert((res as any).errormsg);
      } else if (res.success && !res.res) {
        alert('旧密码输入错误');
      }
    });
  }
  return() {
    // window.history.back(-1);
    this.router.navigate(['/home']);
  }

  checkValidate(isSubmit?: boolean) {
    const form = this.securityForm;

    for (const field in UpdatepswComponent.ErrorMessages) {

      const control = form.controls[field];

      if (control && control.valid) {
        this.messages[field] = '';
      }
      if (control && (control.dirty || isSubmit) && !control.valid) {
        const messages = UpdatepswComponent.ErrorMessages[field];
        if (control.errors) {
          this.messages[field] = messages[Object.keys(control.errors)[0]];
        }
      }

    }
  }

  static ErrorMessages = {
    password: {
      required: '旧密码不能为空',
      hasError: '旧密码输入错误'
    },
    newPassword: {
      required: '密码不能为空',
      pattern: '大于6位，必须由数字，字母共同组成'
    },
    confirmPassword: {
      required: '确认密码不能为空',
      pattern: '两次密码不一样'
    }
  };
}
